﻿CREATE PROCEDURE [dbo].[UpdateStorageInfosForUser]
	@iid uniqueidentifier 
AS
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	declare @lastsubmit datetime = (
		select top 1 [Submission]
		from [UserStorageInfos]
		where [InstanceId]=@iid
		order by [Submission] desc
		);

	merge [UserStorageInfosLatest] t
	using (select * from [UserStorageInfos] where [InstanceId]=@iid and [Submission]=@lastsubmit) s
	on t.[InstanceId]=s.[InstanceId]
	and t.[InstanceId]=@iid
	when matched then
		update set [Submission]=s.[Submission], [AppFoldersSize]=s.[AppFoldersSize],
			[BackupSize]=s.[BackupSize], [OperatingSystemSize]=s.[OperatingSystemSize],
			[SharedFoldersSize]=s.[SharedFoldersSize], [SharedFoldersDupSize]=s.[SharedFoldersDupSize],
			[StorageFreeSpace]=s.[StorageFreeSpace], [StorageSize]=s.[StorageSize],
			[StorageUsedSpace]=s.[StorageUsedSpace], [StorageChartJpeg]=null
	when not matched by source and t.[InstanceId]=@iid then
		delete
	when not matched by target then
		insert ([InstanceId],[Submission],[AppFoldersSize],[BackupSize],[OperatingSystemSize],[SharedFoldersSize],[SharedFoldersDupSize],[StorageFreeSpace],[StorageSize],[StorageUsedSpace])
		values (s.[InstanceId],s.[Submission],s.[AppFoldersSize],s.[BackupSize],s.[OperatingSystemSize],s.[SharedFoldersSize],s.[SharedFoldersDupSize],s.[StorageFreeSpace],s.[StorageSize],s.[StorageUsedSpace])
	;
RETURN 0